/*
 * @Author: your name
 * @Date: 2022-01-27 11:57:43
 * @LastEditTime: 2022-01-27 21:56:51
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \my-project\src\main\dom.js
 */
import fs from 'fs';
import { ipcMain,webContents   } from 'electron';  
import path from 'path'
const paths = true
  ? `${path.resolve(__dirname,'../../../db.json')}`
  : `${path.resolve(__dirname,'../../db.json')}`
// 读取文件
const readdbs = (args) => { 
  return new Promise((resolve, inject) => {
    fs.readFile(`${paths}`, (err, data) => {  
      if (err) {
        inject(false);
      }  
      try{
        resolve(data.toString());
      }catch(err){
        resolve(data.toString());
      } 
    })
  })
}
// readdbs().then(res=>{
//    console.log(res);
// })

// 每天计划只能写一条，一条200字
// 创建+更新 时间格式yyyy-mm-dd
const createNote = (time, note) => {
  return new Promise((resolve, inject) => {
    readdbs('db').then(res => {
      if (res) {
        let jsonstr = typeof res == 'object'?res:JSON.parse(res);
        jsonstr[time] = note;
        fs.writeFile(paths, JSON.stringify(jsonstr), (err) => {
          if (err){
            resolve(false)
          }else{
            resolve(JSON.stringify({[time]:note}));
          }
        });
      }
    })
  })
}
// 移除
const deleteNote = (time) => {
  return new Promise((resolve, inject) => {
    readdbs('db').then(res => {
      if (res) {
        let jsonstr = typeof res == 'object'?res:JSON.parse(res);
        delete jsonstr[time]
        fs.writeFile(paths, JSON.stringify(jsonstr), (err) => {
          if (err){
            resolve(false)
          }else{
            resolve(true)
          } 
        });
      }
    })
  })
}




// deleteNote("2023").then((res)=>{
//     console.log(res)
// })

// IPC通信
// 获取数据
ipcMain.on('inits', (e, args) => { 
 
  readdbs(args).then(res => { 
    console.log(res)
    // e.sender.send('getdatas',res)
  }) 
}) 

// 创建数据
ipcMain.on('create', (e, args) => { 
  let {time,data } = JSON.parse(args);
 
  createNote(time, data).then(res => {
    e.sender.send('createresult', res)   
  })
}) 

// 移除数据
ipcMain.on('delete', (e, args) => { 
  deleteNote(args).then(res => {
    if(res){
      e.sender.send('deleteresult', args)
    } 
   })
}) 
// 清空数据
ipcMain.on('clearall',(e,args)=>{
  fs.writeFile(paths, JSON.stringify({}), (err) => { 
    e.sender.send('clearallres', true)
  })
})

// 开启子线程，通过子线程对数据库进行初始化，或者获取初始化数据，
 export const inits = (cbs)=>{
 
  readdbs('db').then(res => {  
 
    cbs(res)
  },(err)=>{
    cbs('');
  })  
 }
 
 




































 


 